package mashuaiproject.mashuaiproject.advice;


import com.alibaba.fastjson.JSON;
import mashuaiproject.mashuaiproject.dto.ResultDto;
import mashuaiproject.mashuaiproject.exption.CustomizeCode;
import mashuaiproject.mashuaiproject.exption.CustomizeException;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//异常处理
@ControllerAdvice
public class CustomizeExceptionHandler {

    @ExceptionHandler(Exception.class)
    ModelAndView handel(Throwable ex, Model model, HttpServletRequest request
    , HttpServletResponse response){
       String  contentType= request.getContentType();
       if(contentType!=null){
           if(contentType.equals("application/json")){
               ResultDto resultDto=null;

               if(ex instanceof CustomizeException){
                   resultDto= (ResultDto) ResultDto.erroOf((CustomizeException) ex);
               }else{
                   resultDto= ResultDto.erroOf(CustomizeCode.SYS_ERRor);
               }
               try {
                   response.setContentType("application/json");
                   response.setStatus(200);
                   response.setCharacterEncoding("utf-8");
                   PrintWriter writer = response.getWriter();
                   writer.write(JSON.toJSONString(resultDto));
                   writer.close();
               }catch (IOException ioe){

               }
           }else {
               //如果当前异常是自定义的
               if(ex instanceof CustomizeException){
                   model.addAttribute("message",ex.getMessage());
               }else{
                   model.addAttribute("message",CustomizeCode.SYS_ERRor.getMessage());
               }
               return  new ModelAndView("error");//返回错误的页面
           }
       }

        return null;
    }

}
